// 罗马数字映射表
export const ROMAN_TO_NUMBER = {
    'I': 1, 'Ⅰ': 1,
    'Ⅱ': 2,
    'Ⅲ': 3,
    'Ⅳ': 4,
    'Ⅴ': 5,
    'Ⅵ': 6,
    'Ⅶ': 7,
    'Ⅷ': 8,
    'Ⅸ': 9,
    'Ⅹ': 10,
    'Ⅺ': 11,
    'Ⅻ': 12
};

// 数字到罗马数字的映射
export const NUMBER_TO_ROMAN = {
    1: 'Ⅰ',
    2: 'Ⅱ',
    3: 'Ⅲ',
    4: 'Ⅳ',
    5: 'Ⅴ',
    6: 'Ⅵ',
    7: 'Ⅶ',
    8: 'Ⅷ',
    9: 'Ⅸ',
    10: 'Ⅹ',
    11: 'Ⅺ',
    12: 'Ⅻ'
};

// 获取下一级罗马数字
const getNextLevel = (code) => {
    console.log(code);
    const currentNum = ROMAN_TO_NUMBER[code];
    return currentNum ? NUMBER_TO_ROMAN[currentNum + 1] : '';
};

// 提取罗马数字部分
export const extractLevel = (code) => {
    const match = code.match(/(I|Ⅰ|Ⅱ|Ⅲ|Ⅳ|Ⅴ|Ⅵ|Ⅶ|Ⅷ|Ⅸ|Ⅹ|Ⅺ|Ⅻ)+/);
    return match ? match[0] : code;
};

// 提前前缀
export const getPrefix = (code) => {
    const match = code.match(/^([DQY]?)(.*)/);
    return match ? match[1] : '';
};

// 获取表计类型前缀
export const getTypePrefix = (type) => {
    switch (type) {
        case 1: return '';  // 水表无前缀
        case 2: return 'D'; // 电表前缀
        case 3: return 'Q'; // 气表前缀
        case 6: return 'Y'; // 压力表前缀
        default: return '';
    }
};


// 获取表计等级数字
export const getCurrentLevel = (levelCode) => {
    const romanPart = levelCode.match(/[Ⅰ-Ⅻ]/)?.[0];
    if (!romanPart) return 0;
    return ROMAN_TO_NUMBER[romanPart] || 0;
};

export function getNextSubCode(parentCode, existingCodes) {
    // 如果不是数组直接返回空字符串
    if (!Array.isArray(existingCodes)) {
        return '';
    }

    if (!parentCode || !existingCodes || existingCodes.length === 0) {
        return ''
    }

    // 处理父节点为"无"的情况
    if (parentCode === "无") {
        // 筛选出一级表计编码
        const firstLevelCodes = existingCodes.filter(code => code.includes('Ⅰ'));
        console.log(firstLevelCodes);

        if (firstLevelCodes.length === 0) {
            return getPrefix(existingCodes[0]) + extractLevel(firstLevelCodes[0]) + '-01';
        }
        //获取最大的序号
        const maxRoman = Math.max(...firstLevelCodes.map(code => code.split('-')[1]));
        // 返回下一个罗马数字
        return getPrefix(firstLevelCodes[0]) + extractLevel(firstLevelCodes[0]) + '-' + (parseInt(maxRoman) + 1).toString().padStart(2, '0');
    }

    try {
        const [prefix, ...rest] = parentCode.split('-');
        const parentLevel = extractLevel(prefix);
        const nextLevel = getNextLevel(parentLevel);

        if (!nextLevel) {
            return '';
        }

        const newPrefix = prefix.replace(parentLevel, nextLevel);
        const childCodes = existingCodes.filter(code => code.startsWith(`${newPrefix}-`));

        if (childCodes.length === 0) {
            return `${newPrefix}-01`;
        }

        const maxNum = Math.max(...childCodes.map(code => parseInt(code.split('-')[1])));
        const nextNum = String(maxNum + 1).padStart(2, '0');
        return `${newPrefix}-${nextNum}`;
    } catch (error) {
        console.error('getNextSubCode error:', error);
        return '';
    }
}

// 获取下一个序列号
export function getNextSequence(targetLevel, existingNumbers) {
    try {
        const prefix = targetLevel.match(/^[DQ]?/)[0];
        const romanNumeral = targetLevel.replace(/^[DQ]/, '');

        if (!ROMAN_TO_NUMBER[romanNumeral]) {
            throw new Error('不支持的层级编号：' + targetLevel);
        }

        const regex = new RegExp(`${targetLevel}-\\d{2}`);
        const targetLevelNumbers = existingNumbers.filter(num => regex.test(num));

        if (targetLevelNumbers.length === 0) {
            return "01";
        }

        const sequences = targetLevelNumbers.map(num => {
            const match = num.match(/-(\d{2})/);
            return match ? parseInt(match[1]) : 0;
        });

        const maxSequence = Math.max(...sequences);
        const nextSequence = (maxSequence + 1).toString().padStart(2, '0');

        if (parseInt(nextSequence) > 99) {
            throw new Error('序号超出范围（最大支持到99）');
        }

        return nextSequence;
    } catch (error) {
        console.error('getNextSequence error:', error);
        throw error;
    }
}